package com.nega.commons.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.nega.commons.filter.ShiroUrlPermissionsFilter;
import com.nega.commons.shiro.UserAuthorizingRealm;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
 
/**
 * Shiro配置类
 * @author Garc
 *
 */
@Configuration
public class ShiroConfiguration {

    /**
     * 配置shiro过滤器
     */
    @Bean("shiroFilter")                                                                                                                                                                                                               
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean=new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        Map<String,String> filterChainMap = new LinkedHashMap<>();
        filterChainMap.put("/mem/login*","anon");
        filterChainMap.put("/mem/logout*","anon");
        filterChainMap.put("/mem/register*","anon");
        filterChainMap.put("/mem/valcheck*","anon");
        filterChainMap.put("/mem/active*","anon");
        filterChainMap.put("/center/search*","anon");
        filterChainMap.put("/scan*","anon");
        filterChainMap.put("/static/**","anon");
        filterChainMap.put("/**","authc,perms");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainMap);
        shiroFilterFactoryBean.setLoginUrl("/mem/login");
        shiroFilterFactoryBean.setSuccessUrl("/scan");
        shiroFilterFactoryBean.setUnauthorizedUrl("/mem/login");
        //自定义鉴权方式(动态URL鉴权)
        Map<String, Filter> filter = new HashMap<>();
        filter.put("perms",new ShiroUrlPermissionsFilter());
        shiroFilterFactoryBean.setFilters(filter);
        return shiroFilterFactoryBean;
    }

    @Bean
    public UserAuthorizingRealm userAuthorizingRealm(){
        return new UserAuthorizingRealm();
    }

    /**
     * 配置安全管理器
     */
    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(userAuthorizingRealm());
        return securityManager;
    }

    @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }
 
}